package com.wk.note;

/**
 * @author WK
 * @version 1.0
 * @date 2024-07-11 19:33
 */
//package com.example.conceptnotebookjava;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NoteManager {

    private static final String FILE_PATH = "notes.json";
    private List<Note> notes;
    private ObjectMapper mapper;

    public NoteManager() {
        this.notes = new ArrayList<>();
        this.mapper = new ObjectMapper();
        loadNotesFromFile();
    }

    private void loadNotesFromFile() {
        try {
            File file = new File(FILE_PATH);
            if (file.exists()) {
                notes = mapper.readValue(file, new TypeReference<List<Note>>() {});
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveNotesToFile() {
        try {
            File file = new File(FILE_PATH);
            mapper.writeValue(file, notes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addOrUpdateNote(Note note) {
        // Check if note already exists by comparing IDs or other unique identifiers
        // If exists, update; if not, add new note
        if (note.getId() == null) {
            note.setId(System.currentTimeMillis()); // Generate unique ID
            notes.add(note);
        } else {
            for (int i = 0; i < notes.size(); i++) {
                if (notes.get(i).getId().equals(note.getId())) {
                    notes.set(i, note);
                    break;
                }
            }
        }
        saveNotesToFile();
    }

    public List<Note> getAllNotes() {
        return notes;
    }

    public void deleteNote(Note note) {
        notes.removeIf(n -> n.getId().equals(note.getId()));
        saveNotesToFile();
    }
}
